/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 20, 2012  8:22:44 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.fi.outbound
 * File Name : FiVcGlpostingOutbService.java
 * TODO
 */
package sap.business.fi.outbound;

import java.util.ArrayList;
import java.util.List;

import jpa.entitys.synchro.staging.FiArinvoicereceOutb;
import jpa.entitys.synchro.staging.FiVcGlpostingOutb;
import jpa.entitys.synchro.staging.SdCustomerOutb1;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.FiVcGlpostingOutbServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class FiVcGlpostingOutbService extends SynchroOutAbstract {
	
	
	private static final Logger log = Logger.getLogger(FiVcGlpostingOutbService.class);
	private FiVcGlpostingOutbServices fiVcGlpostingOutbServ; 
	/**
	 * 
	 */
	public FiVcGlpostingOutbService() {
		// TODO Auto-generated constructor stub
		try {
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			
			log.info("value_list.size : " + value_list.size());			
			log.info("table.getNumRows : " + jcoTable.getNumRows());
			
			for (Object obj : value_list) 
	        {
				FiVcGlpostingOutb model = (FiVcGlpostingOutb)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId());
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				jcoTable.setValue("INTERFACE_NO", "FI-T1-080");				
				jcoTable.setValue("BUKRS", model.getSapCompanyCode());
				
				jcoTable.setValue("CHARGE_CODE", model.getChargeCode());
				jcoTable.setValue("CHARGE_NAME", model.getDescription());
				jcoTable.setValue("BLDAT", model.getVoucherDate());
				jcoTable.setValue("BUDAT", model.getVoucherDate());
				jcoTable.setValue("WAERS", model.getCurrency());
				jcoTable.setValue("KURSF", model.getExchangeRate());
				jcoTable.setValue("XBLNR", model.getChargePeriod());
				jcoTable.setValue("HKONT", model.getCustomerCode());
				jcoTable.setValue("PROMIS_UNIT_CODE", model.getUnitNumber());
				jcoTable.setValue("PLANT_CODE", model.getSapPlantCode());
				jcoTable.setValue("ZUONR", model.getContractRefNo());
				jcoTable.setValue("SGTXT", CommonService.IsNullRString(model.getRefInvoiceNo()) + "," + CommonService.IsNullRString(model.getNarration()));
				jcoTable.setValue("WRBTR", model.getFurnitureAmount());
				
				jcoTable.setValue("STATUS", model.getStatus());
				
				
	        }
		}
		
		super.SynchroToSap(jcoFunction, jcoTable, value_list);
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		List<FiVcGlpostingOutb> lst = new ArrayList<FiVcGlpostingOutb>();				

			if(!jcoTable_return.isEmpty()){
				log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
				for(int i = 0; i < jcoTable_return.getNumRows(); i++)
				{
					jcoTable_return.setRow(i);			
					FiVcGlpostingOutb model = fiVcGlpostingOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
					log.info(CommonJCOReturn.toString(jcoTable_return));
					
					if(model != null){
						
						model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
						model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
						model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
						model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
						model.setIsactive("Y");
						model.setIssync("Y");
						
						lst.add(model);
					}
				}
			}else
				log.info(CommonJCOReturn.toString(jcoTable_return));
			
			fiVcGlpostingOutbServ.Updated(lst);
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	
	private void UpdateStagingWhenError(List<FiVcGlpostingOutb> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<FiVcGlpostingOutb> newlst = new ArrayList<FiVcGlpostingOutb>();
				for(FiVcGlpostingOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new FiVcGlpostingOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	public void SendToSAP(List<FiVcGlpostingOutb> value_list) throws Exception
	{
		try{
			if(!CommonService.IsNull(value_list)){
				
				this.sap_bapi = "ZIN_FI_DOC_POSTING";
				this.sap_table = "ACCT_DATA";
				this.sap_table_return = "RETURN";
				this.jco_conn  = new Connection();
				
				//Get SAP BAPI function 
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				fiVcGlpostingOutbServ = new FiVcGlpostingOutbServices(this.emSynchro);
				//List<FiVcGlpostingOutb> value_list = fiVcGlpostingOutbServ.findIsSync("N");
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
			}
		}catch(Exception e){
			UpdateStagingWhenError(value_list, e);
			log.error(e);
			throw e;
		}
	}
	
	private void Start() throws Exception
	{
		this.sap_bapi = "ZIN_FI_DOC_POSTING";
		this.sap_table = "ACCT_DATA";
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();
		
		//Get SAP BAPI function 
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		fiVcGlpostingOutbServ = new FiVcGlpostingOutbServices(this.emSynchro);
		List<FiVcGlpostingOutb> value_list = fiVcGlpostingOutbServ.findIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}
	

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		
//		try{
//			
//			FiVcGlpostingOutbService obj = new FiVcGlpostingOutbService();
//			obj.Start();
//			
//		}catch(Exception ex)
//		{
//			ex.printStackTrace();
//			log.error(ex);
//		}
//	}

}
